package com.rds.system.service.impl;

import com.rds.common.constant.UserConstants;
import com.rds.common.core.domain.TreeSelect;
import com.rds.common.core.domain.entity.SysCompany;
import com.rds.common.core.domain.entity.SysDept;
import com.rds.common.core.text.Convert;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.StringUtils;
import com.rds.system.mapper.SysCompanyMapper;
import com.rds.system.mapper.SysDeptMapper;
import com.rds.system.service.ISysCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysCompanyServiceImpl implements ISysCompanyService {
    @Autowired
    private SysCompanyMapper companyMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Override
    public List<SysCompany> selectSysCompanyList(SysCompany sysCompany) {
        return companyMapper.selectSysCompanyList(sysCompany);
    }

    /**
     * 构建前端所需要树结构
     * @param sysCompany 公司列表
     * @return 树结构列表
     */
    @Override
    public List<SysCompany> buildCompanyTree(List<SysCompany> sysCompany) {
        List<SysCompany> returnList=new ArrayList<SysCompany>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysCompany company:sysCompany) {
            tempList.add(company.getCompanyId());
        }
        for (Iterator<SysCompany> iterator=sysCompany.iterator(); iterator.hasNext();) {
            SysCompany company=(SysCompany)iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(company.getParentId())){
                recursionFn(sysCompany, company);
                returnList.add(company);
            }
        }
        if (returnList.isEmpty()){
            returnList = sysCompany;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * @param sysCompany 公司列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildCompanyTreeSelect(List<SysCompany> sysCompany) {
        List<SysCompany> companyTrees=buildCompanyTree(sysCompany);
        return companyTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<SysCompany> selectCompanyListByRoleId(Long roleId) {
        return companyMapper.selectCompanyListByRoleId(roleId);
    }

    /**
     * 根据公司ID查询信息
     * @param companyId 公司ID
     * @return 部门信息
     */
    @Override
    public SysCompany selectSysCompanyById(Long companyId) {
        return companyMapper.selectSysCompanyById(companyId);
    }

    /**
     * 根据ID查询所有子公司（正常状态）
     * @param companyId 公司ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenCompanyById(Long companyId) {
        return companyMapper.selectNormalChildrenCompanyById(companyId);
    }

    /**
     * 新增保存公司信息
     * @param sysCompany 公司信息
     * @return 结果
     */
    @Override
    public int insertSysCompany(SysCompany sysCompany) {
        if(sysCompany.getStatus().equals("正常")){
            sysCompany.setStatus("0");
        }else if(sysCompany.getStatus().equals("停用")){
            sysCompany.setStatus("1");
        }else{
            sysCompany.setStatus("0");
        }
        sysCompany.setDelFlag('0');
        sysCompany.setCreateBy(SecurityUtils.getUsername());
        sysCompany.setCreateTime(DateUtils.getNowDate());
        int row;
        SysCompany info=companyMapper.selectSysCompanyById(sysCompany.getParentId());
        if("2".equals(sysCompany.getCompanyOrDept())){
            SysDept dept=new SysDept();
            if(info!=null){
                dept.setAncestors(info.getAncestors() + "," + sysCompany.getParentId());
            }else{
                SysDept infos=deptMapper.selectDeptById(sysCompany.getParentId());
                dept.setAncestors(infos.getAncestors() + "," + sysCompany.getParentId());
            }
            dept.setParentId(sysCompany.getParentId());
            dept.setDeptName(sysCompany.getDeptName());
            dept.setCharge(sysCompany.getCharge());
            dept.setCompanyId(sysCompany.getParentId());
            dept.setOrderNum(""+sysCompany.getOrderNum());
            dept.setTel(sysCompany.getTel());
            dept.setEmail(sysCompany.getEmail());
            dept.setCreateBy(SecurityUtils.getUsername());
            row=deptMapper.insertDept(dept);
        }else {
            sysCompany.setAncestors(info.getAncestors() + "," + sysCompany.getParentId());
            row= companyMapper.insertSysCompany(sysCompany);
        }
        return row;
    }

    /**
     * 修改保存公司信息
     * @param sysCompany 公司信息
     * @return 结果
     */
    @Override
    public int updateSysCompany(SysCompany sysCompany) {
        sysCompany.setUpdateBy(SecurityUtils.getUsername());
        SysCompany newParentCompany=companyMapper.selectSysCompanyById(sysCompany.getParentId());
        SysCompany oldCompany=companyMapper.selectSysCompanyById(sysCompany.getCompanyId());
        if (StringUtils.isNotNull(newParentCompany) && StringUtils.isNotNull(oldCompany)){
            String newAncestors = newParentCompany.getAncestors() + "," + newParentCompany.getCompanyId();
            String oldAncestors = oldCompany.getAncestors();
            sysCompany.setAncestors(newAncestors);
            updateCompanyChildren(sysCompany.getCompanyId(), newAncestors, oldAncestors);
        }
        if(sysCompany.getStatus().equals("正常")){
            sysCompany.setStatus("0");
        }else if(sysCompany.getStatus().equals("停用")){
            sysCompany.setStatus("1");
        }else{
            sysCompany.setStatus("0");
        }
        int result;
        if("2".equals(sysCompany.getCompanyOrDept())) {//公司跟部门都不为空的时候保存部门信息
            SysDept dept=new SysDept();
            dept.setDeptId(sysCompany.getCompanyId());
            dept.setOrderNum(""+sysCompany.getOrderNum());
            dept.setStatus(sysCompany.getStatus());
            dept.setTel(sysCompany.getTel());
            dept.setEmail(sysCompany.getEmail());
            dept.setCharge(sysCompany.getCharge());
            dept.setDeptName(sysCompany.getDeptName());
            result=deptMapper.updateDept(dept);
        } else {
            result=companyMapper.updateSysCompany(sysCompany);
        }
        if("0".equals(sysCompany.getStatus()) && StringUtils.isNotEmpty(sysCompany.getAncestors()) && !StringUtils.equals("0", sysCompany.getAncestors())){
            // 如果该公司是启用状态，则启用该公司的所有上级部门
            updateParentCompanyStatusNormal(sysCompany);
        }
        return result;
    }

    @Override
    public int deleteSysCompany(Long companyId) {
        return companyMapper.deleteSysCompany(companyId);
    }

    /**
     * 校验公司名称是否唯一
     * @param sysCompany 公司信息
     * @return 结果
     */
    @Override
    public String checkCompanyNameUnique(SysCompany sysCompany) {
        Long deptId = StringUtils.isNull(sysCompany.getCompanyId()) ? -1L : sysCompany.getCompanyId();
        SysCompany info=companyMapper.checkCompanyNameUnique(sysCompany.getCompanyName(), sysCompany.getParentId());
        if (StringUtils.isNotNull(info) && info.getCompanyId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 是否存在子节点
     * @param companyId 公司ID
     * @return 结果
     */
    @Override
    public boolean hasChildByCompanyId(Long companyId) {

        int result = companyMapper.hasChildByCompanyId(companyId);
        return result > 0 ? true : false;
    }

    /**
     * 修改子元素关系
     * @param companyId 被修改的公司ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCompanyChildren(Long companyId, String newAncestors, String oldAncestors)
    {
        List<SysCompany> children=companyMapper.selectChildrenCompanyById(companyId);
        for (SysCompany child:children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0){
            companyMapper.updateCompanyChildren(children);
        }
    }

    /**
     * 修改该公司的父级部门状态
     * @param sysCompany 当前公司
     */
    private void updateParentCompanyStatusNormal(SysCompany sysCompany){
        String ancestors = sysCompany.getAncestors();
        Long[] companyId = Convert.toLongArray(ancestors);
        companyMapper.updateCompanyStatusNormal(companyId);
    }

    /**
     * 删除公司管理信息
     *
     * @param companyId 公司ID
     * @return 结果
     */
    @Override
    public int deleteCompanyById(Long companyId) {
        return companyMapper.deleteCompanyById(companyId);
    }

    @Override
    public SysCompany selectSysCompanyDeptById(Long companyId) {
        return companyMapper.selectSysCompanyDeptById(companyId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysCompany> list,SysCompany t){
        // 得到子节点列表
        List<SysCompany>  childList=getChildList(list, t);
        t.setChildren(childList);
        for (SysCompany tChild:childList) {
            if (hasChild(list, tChild)){
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<SysCompany> getChildList(List<SysCompany> list,SysCompany t){
        List<SysCompany> tlist=new ArrayList<SysCompany>();
        Iterator<SysCompany> it = list.iterator();
        while (it.hasNext()){
            SysCompany n=(SysCompany)it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCompanyId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysCompany> list,SysCompany t){
        return getChildList(list, t).size() > 0 ? true : false;
    }


    /**
     * 根据公司名称查询公司id
     * @param companyName 公司ID
     * @return 结果
     */
    public Long selectCompanyIdByName(String companyName){
        return companyMapper.selectCompanyIdByName(companyName);
    }

    @Override
    public List<Map> selectCompanyListCompanyAndDep() {
        return companyMapper.selectCompanyListCompanyAndDep();
    }
}
